package com.huawei.esdk.tpoa.tools.action;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;
import org.apache.log4j.Logger;
import com.huawei.esdk.tpoa.tools.cxf.autogen.SiteParamEx;
import com.huawei.esdk.tpoa.tools.cxf.service.SMCService;
import com.huawei.esdk.tpoa.tools.cxf.utils.PropertiesUtils;

public class CreateScript
{
    public static final String FILENAME = "TempScript.ps1";

    private static BufferedWriter writer;

    public static List<SiteParamEx> sites = null;

    private static String smcUrl = null;

    public static String userName = null;

    private static String password = null;

    private static String userDomain = null;

    private static final Logger LOGGER = Logger.getLogger(CreateScript.class
            .getName());

    private static boolean loadTpSite()
    {
        SMCService smcService = SMCService.getInstance(CreateScript.smcUrl);
        int loginErrorCode = smcService.login(CreateScript.userName,
                CreateScript.password);
        if (0 == loginErrorCode)
        {
            LOGGER.info("Login to the SMC is successful.");
        }
        else
        {
            LOGGER.info("Fail to login SMC,error code :" + loginErrorCode
                    + ",please check eSDK TP Interface reference document.");
            return false;
        }

        sites = smcService.querySites();
        if (null != sites)
        {
            LOGGER.info("Query of TP sites is successful,The number of TP sites is "
                    + sites.size());
        }
        else
        {
            LOGGER.info("Fail to query TP sites");
            return false;
        }

        smcService.logout();
        return true;
    }

    private static void createShellFile() throws IOException
    {
        File newFile = new File(CreateScript.FILENAME);

        if (!newFile.exists())
        {
            newFile.createNewFile();
        }
    }

    private static void createShellScript() throws IOException
    {
        File file = new File(CreateScript.FILENAME);

        FileOutputStream out = new FileOutputStream(file);
        writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-16"));

        StringBuffer sb = new StringBuffer();

        /**
         * 莫斯科航管局项目新需求开始
         * 
         */
        // OrganizationalUnit default name: Huawei_SiteGroup
        String defaultOU = PropertiesUtils
                .getValue("default_OrganizationalUnit_name");

        // import the Active Directory module
        String importADModule = "Import-Module ActiveDirectory;\n";

        // create new AD OrganizationalUnit
        String createADOU = "New-ADOrganizationalUnit -Name '" + defaultOU
                + "';\n";
        sb.append(importADModule).append(createADOU);

        String getDatabaseName = "$database = Get-MailboxDatabase;$databaseName = $database.Name;";
        sb.append(getDatabaseName);

  /*
        String roomListName = PropertiesUtils.getValue("HW.TP.RoomList.Name");
        String createRoomListScript = "New-DistributionGroup -Name '"
                + roomListName + "' -Type: 'Distribution' -SamAccountName: '"
                + roomListName + "';\n";
        sb.append(createRoomListScript);

        // 增加扩增属性
        String ResourcePropertySchema = PropertiesUtils
                .getValue("HW.TP.ResourcePropertySchema.Name");
        String addResourcePropertySchema = "$ResourceConfiguration = Get-ResourceConfig;$ResourceConfiguration.ResourcePropertySchema.Add('Room/"
                + ResourcePropertySchema
                + "');Set-ResourceConfig -ResourcePropertySchema $ResourceConfiguration.ResourcePropertySchema;\n";
        sb.append(addResourcePropertySchema);
*/
        
        // 职务
        String title = PropertiesUtils.getValue("HW.TP.Room.Title");

        if (null != sites)
        {
            for (int i = 0; i < sites.size(); i++)
            {
                SiteParamEx site = sites.get(i);
                String roomSiteUri = site.getUri();

                sb.append("New-Mailbox -Name '")
                        .append(site.getName())
                        .append("' -Alias '")
                        .append(roomSiteUri)
                        .append("' -UserPrincipalName '")
                        .append(roomSiteUri + "@" + userDomain.toLowerCase()
                                + ".com").append("' -FirstName '")
                        .append(site.getName())
                        .append("' -OrganizationalUnit '").append(defaultOU)
                        .append("' -Database $databaseName -Room;\n");
/*
                String addMemberScript = "Add-DistributionGroupMember -Member '"
                        + site.getName()
                        + "' -Identity '"
                        + roomListName
                        + "';\n";

                String addResource = "Set-Mailbox -Identity '" + site.getName()
                        + "' -ResourceCustom ('" + ResourcePropertySchema
                        + "');\n";
*/
                String addCustomeAttr1 = "Set-Mailbox -Identity '"
                        + site.getName() + "' -CustomAttribute1 '" + title
                        + "';\n";
                String addCustomeAttr2 = "Set-Mailbox -Identity '"
                        + site.getName() + "' -CustomAttribute2 '"
                        + site.getUri() + "';\n";
                String addCustomeAttr3 = "Set-Mailbox -Identity '"
                        + site.getName() + "' -CustomAttribute3 '"
                        + site.getName() + "';\n";
                String addCustomeAttr4 = "Set-Mailbox -Identity '"
                        + site.getName() + "' -CustomAttribute4 '"
                        + site.getType().toString() + "';\n";

                String addTitle = "Set-User '" + site.getName() + "' -Title '"
                        + title + "';\n";

//                sb.append(addMemberScript);
//                sb.append(addResource);
                sb.append(addCustomeAttr1);
                sb.append(addCustomeAttr2);
                sb.append(addCustomeAttr3);
                sb.append(addCustomeAttr4);
                sb.append(addTitle);
            }
        }

        if (sb.length() > 0)
        {
            writer.write(sb.toString());
        }
        writer.flush();
    }

    public static void main(String[] args) throws IOException
    {
        if (null != args && 3 < args.length)
        {
            CreateScript.smcUrl = args[0];
            CreateScript.userName = args[1];
            CreateScript.password = args[2];
            CreateScript.userDomain = args[3];
        }
        else
        {
            LOGGER.info("Parameters can't be null");
            return;
        }

        boolean flag = loadTpSite();
        if (flag)
        {
            createShellFile();
            createShellScript();
        }
    }
}
